<!--
 * @Author: Liz.Zheng
 * @Date: 2021-12-07 15:05:42
 * @LastEditTime: 2023-02-16 10:19:22
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 优惠条款
 * @Motto: Write the code. Change the world.
-->

<template>
  <a-card :title="title">
    <template #extra>
      <a-space>
        <a-dropdown
          v-if="canAddDiscountClause"
          placement="bottom"
          :trigger="['click']"
        >
          <a-button type="text">
            <template #icon>
              <PlusCircleOutlined />
            </template>
          </a-button>
          <template #overlay>
            <a-menu @click="handleAddClick">
              <a-menu-item key="top"> 向上插入条款 </a-menu-item>
              <a-menu-divider />
              <a-menu-item key="under"> 向下插入条款 </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
        <a-button type="text" @click="handleRemove">
          <template #icon>
            <CloseOutlined />
          </template>
        </a-button>
      </a-space>
    </template>
    <a-form layout="vertical">
      <a-row :gutter="24" :wrap="true">
        <a-col :sm="24" :md="12" :lg="8" :xl="6">
          <a-form-item label="优惠类型" v-bind="validateInfos.discount_type">
            <a-select
              v-model:value="modelRef.discount_type"
              placeholder="请选择"
              @select="handleDiscountTypeChange"
            >
              <a-select-option
                v-for="item of optionData.discount_type"
                :value="item.key"
                :key="item.key"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :sm="24" :md="12" :lg="8" :xl="6">
          <a-form-item label="起始时间" v-bind="validateInfos.discount_time">
            <a-range-picker
              v-model:value="modelRef.discount_time"
              :valueFormat="dateFormatStr"
              :disabled-date="disabledDate"
            />
          </a-form-item>
        </a-col>
        <template v-if="showDiscountInput">
          <a-col :sm="12" :md="6" :lg="4" :xl="3">
            <a-form-item label="开始期数" v-bind="validateInfos.stage_start">
              <a-input-number
                placeholder="请输入"
                v-model:value="modelRef.stage_start"
                style="width: 100%"
                :min="0"
              />
            </a-form-item>
          </a-col>
          <a-col :sm="12" :md="6" :lg="4" :xl="3">
            <a-form-item label="期长" v-bind="validateInfos.stage_num">
              <a-input-number
                placeholder="请输入"
                v-model:value="modelRef.stage_num"
                style="width: 100%"
                :min="0"
              />
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :lg="8" :xl="6">
            <a-form-item
              :label="discountLabel"
              v-bind="validateInfos.discount_num"
            >
              <a-input-group compact>
                <a-input-number
                  placeholder="请输入"
                  v-model:value="modelRef.discount_num"
                  style="width: 80%"
                  :min="0"
                />
                <span class="num-input-suffix">{{
                  modelRef.discount_type == "select_2" ? "折" : "元"
                }}</span>
              </a-input-group>
            </a-form-item>
          </a-col>
        </template>
        <a-col :sm="24" :md="12" :lg="8" :xl="6" v-if="!showDiscountInput">
          <a-form-item v-bind="validateInfos.exempt_lease_type">
            <template #label>
              <a-space>
                <span>免租期划分方式</span>
                <a-tooltip>
                  <template #title>
                    <div>
                      <span style="font-weight: 700">免租期划入租期：</span>
                      生成的账单依然保持付款周期的时间段，只是该期账单的金额减少。例：1.1-12.31，3月一付，免租4.1-4.30；则第一笔账单是1.1-3.31，第二笔账单是4.1-6.30，只是第二笔账单费用减少了一个月。
                    </div>
                    <div style="margin-top: 5px">
                      <span style="font-weight: 700">免租期不划入租期：</span>
                      以免租时间段截断付款周期的计算。之前为一笔账单，之后重新计算。例：1.1-12.31，3月一付，免租4.1-4.30，第一笔账单是1.1-3.31，第二笔是5.1-7.31。
                    </div>
                  </template>
                  <question-circle-outlined />
                </a-tooltip>
              </a-space>
            </template>
            <a-select
              v-model:value="modelRef.exempt_lease_type"
              placeholder="请选择"
            >
              <a-select-option
                v-for="item of exemptLeaseTypeList"
                :value="item.key"
                :key="item.key"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :sm="24" :md="12" :lg="8" :xl="6">
          <a-form-item label="备注" v-bind="validateInfos.remark">
            <a-textarea
              v-model:value="modelRef.remark"
              placeholder="请输入"
              :rows="{ min: 2, max: 4 }"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
</template>

<script>
import { defineComponent, reactive, watch, ref, computed, nextTick } from "vue";
import {
  CloseOutlined,
  PlusCircleOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { Form, message } from "ant-design-vue";
import store from "../../../../store";
import utils from "../../../../common/utils/utils";
import moment from "moment";
import _ from "lodash";
import {useRoute} from "vue-router";
const useForm = Form.useForm;

export default defineComponent({
  name: "NormalClause",
  props: {
    index: {
      type: Number,
      default: 0,
    },
    // 触发验证
    trigger: {
      type: Number,
      default: 0,
    },
    paneFrom: {
      type: String,
      default: "default",
    },
    content: {
      type: Object,
      default: () => {
        return {};
      },
    },
    canAddDiscountClause: {
      type: Boolean,
      default: false,
    },
  },
  components: { PlusCircleOutlined, CloseOutlined, QuestionCircleOutlined },
  setup(props, context) {
    const $route = useRoute();
    const dateFormatStr = "YYYY-MM-DD";
    const today = moment().format(dateFormatStr);
    const todayAfterMonth = moment().add(1, "months").format(dateFormatStr);
    const contractDateRange = computed(() => store.getters.contractDateRange);
    const disabledDate = (current) => {
      const { startDate, endDate } = contractDateRange.value;
      return (
        current < moment(startDate).startOf("day") ||
        current > moment(endDate).endOf("days")
      );
    };

    const title = computed(() => {
      return "优惠条款" + (props.index + 1);
    });
    const modelRef = reactive({
      discount_type: undefined,
      discount_time: [today, todayAfterMonth],
      exempt_lease_type: undefined,
      remark: "",
    });
    const rulesRef = reactive({
      discount_type: [{ required: true, message: "必填" }],
      discount_time: [{ required: true, message: "必填" }],
      // exempt_lease_type: [{ required: true, message: "必填" }],
    });

    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const validateForm = () => {
      validate()
        .then(() => {
          let params = JSON.parse(JSON.stringify(modelRef));
          params.discount_start_time = params.discount_time[0];
          params.discount_end_time = params.discount_time[1];
          delete params.discount_time;
          context.emit("success", {
            type: "discount",
            content: params,
          });
        })
        .catch(() => {
          context.emit("fail", {
            type: "normal",
          });
        });
    };

    const showDiscountInput = ref(false);
    const discountLabel = ref("");
    const handleDiscountTypeChange = (value) => {
      discountLabel.value = "";
      if (["select_1", "select_5"].includes(value)) {
        showDiscountInput.value = false;
        getExemptLeaseType();
        setModelAndRule({
          keys: ["stage_start", "stage_num", "discount_num"],
          type: "del",
        });
      } else {
        const option = optionData.value.discount_type.find(
          (item) => item.key == value
        );
        discountLabel.value = option.name;
        showDiscountInput.value = true;
        setModelAndRule({
          keys: ["stage_start", "stage_num", "discount_num"],
          type: "add",
        });
        delete modelRef.exempt_lease_type;
      }
    };
    const numberRule = [
      {
        required: true,
        validator: (rules, value) => utils.pNumberValidator(rules, value),
        trigger: "change",
      },
    ];
    const setModelAndRule = (params) => {
      const { keys, type } = params;
      const { content } = props;
      if (type == "add") {
        for (let key of keys) {
          modelRef[key] = content[key] || "";
          rulesRef[key] = numberRule;
        }
      }
      if (type == "del") {
        for (let key of keys) {
          delete modelRef[key];
          delete rulesRef[key];
        }
      }
    };

    const isRenewal = computed(
      () => $route.query.editType == "renewal"
    );

    const renewalDetail = computed(() => {
      if (isRenewal.value) {
        return {
          originId: $route.query.id,
          startDate: $route.query.startDate,
          endDate: $route.query.endDate,
          duration: $route.query.duration,
        }
      } else {
        return {}
      }
    });

    const setDetail = () => {
      const { content, paneFrom } = props;
      if (content && content.discount_type) {
        modelRef.discount_type = content.discount_type;
        if (isRenewal.value) {
          const renewalData = renewalDetail.value;
          if (renewalData.startDate && renewalData.endDate) {
            modelRef.discount_time = [
              renewalData.startDate,
              renewalData.endDate,
            ];
          }
        } else {
          if (content.discount_start_time && content.discount_end_time)
            modelRef.discount_time = [
              content.discount_start_time,
              content.discount_end_time,
            ];
        }
        modelRef.exempt_lease_type = content.exempt_lease_type;
        handleDiscountTypeChange(modelRef.discount_type, content);
        modelRef.remark = content.remark;
        nextTick(() => {
          store.dispatch("SetClauseTabChange", {
            key: paneFrom,
            changed: false,
          });
          watch(modelRef, (value) => {
            const changed =
              store.getters.clauseContentList[props.paneFrom].changed;
            if (!changed) {
              store.dispatch("SetClauseTabChange", {
                key: props.paneFrom,
                changed: true,
              });
            }
          });
        });
      }
    };

    const optionData = ref({});
    const init = () => {
      store.dispatch("ContractInit").then((res) => {
        optionData.value = res;
        if (res.discount_type && res.discount_type.length) {
          modelRef.discount_type = res.discount_type[0].key;
          getExemptLeaseType(true);
        }
        setDetail();
      });
    };

    const exemptLeaseTypeList = ref([]);
    const getExemptLeaseType = (haveInit = false) => {
      exemptLeaseTypeList.value = [];
      const { exempt_lease_type } = optionData.value;
      if (!exempt_lease_type || !exempt_lease_type.length) return;
      if (modelRef.discount_type == "select_1") {
        // 免租期
        exempt_lease_type.forEach((item) => {
          if (["select_1", "select_2"].includes(item.key)) {
            exemptLeaseTypeList.value.push(item);
          }
        });
      }
      if (modelRef.discount_type == "select_5") {
        // 装修期
        exempt_lease_type.forEach((item) => {
          if (["select_3", "select_4"].includes(item.key)) {
            exemptLeaseTypeList.value.push(item);
          }
        });
      }
      if (exemptLeaseTypeList.value.length && haveInit) {
        modelRef.exempt_lease_type = exemptLeaseTypeList.value[0].key;
      }
    };

    const handleRemove = () => {
      context.emit("remove", { index: props.index, type: "discount" });
    };

    const handleAddClick = (e) => {
      const { key } = e;
      context.emit("add", { index: props.index, type: "discount", way: key });
    };

    init();

    watch(
      () => props.trigger,
      (trigger) => {
        if (trigger) {
          validateForm();
        }
      }
    );

    watch(
      () => modelRef,
      (val) => {
        context.emit("dataChange", {
          type: "discount",
          content: _.cloneDeep(modelRef),
        });
      }, {deep: true}
    );

    return {
      title,
      modelRef,
      validateInfos,
      optionData,
      dateFormatStr,
      exemptLeaseTypeList,
      showDiscountInput,
      discountLabel,
      disabledDate,
      handleRemove,
      handleDiscountTypeChange,
      handleAddClick,
    };
  },
});
</script>
